/**
 * 验签名操作类
 */

export class SignUtils {
    /**
     * 将请求参数排序后，拼接成字符串
     * @param data 请求参数
     */
    static getSortedContent(data: Map<string, any>): string {
        let keys = Array.from(data.keys()).sort();
        let index = 0;
        let content: string = "";
        for (let key of keys) {
            let value = data.get(key);
            if(value !== undefined) {
                if (value instanceof Boolean) {
                    value = value ? 'true' : 'false';
                }
                content = content.concat((index == 0 ? "" : "&")).concat(key).concat("=").concat(value);
                index++;
            }
        }
        /**
         * encodeURIComponent 防止中文不一致问题
         */
        //console.warn(content);
        return content;
    }
    /**
     * 随机获取数据
     * @param min 最小数
     * @param max 最大数
     */
    static random(min: number, max: number) {
        return Math.random() * (max - min + 1) + min;
    }
    static isValidKey(
        key: string | number | symbol,
        object: object
    ): key is keyof typeof object {
        return key in object;
    }

    /**
     * 将map数据转json对象
     * @param data
     */
    static map2Json(data: Map<string, any>): Object {
        let json = Object.create(null);
        for (let [k, v] of data) {
            json[k] = v;
        }
        return json;
    }
    /**
     * 将json数据转map对象
     * @param data
     */
    static json2Map(data: Object | undefined): Map<string, any> {
        let map = new Map();
        if (data) {
            for (let k of Object.keys(data)) {
                if (SignUtils.isValidKey(k, data)) {
                    map.set(k, data[k]);
                }
            }
        }
        return map;
    }

    /**
     * 随机UUID
     */
    static uuid(): string {
        let s = [] as Array<any>;
        let hexDigits = "0123456789abcdef";
        for (let i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";
        let uuid = s.join("");
        return uuid
    }
}